package com.eastfair.common.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.eastfair.annotation.annotation.security.PreAuth;
import com.eastfair.auth.api.UserAccountServiceFeign;
import com.eastfair.auth.dto.UserAccountDto;
import com.eastfair.auth.vo.UserAccountVo;
import com.eastfair.boot.controller.SuperController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.common.dto.AttachmentFileDTO;
import com.eastfair.common.dto.AttachmentFilePageQuery;
import com.eastfair.common.dto.AttachmentFileSaveDTO;
import com.eastfair.common.dto.AttachmentFileUpdateDTO;
import com.eastfair.common.entity.AttachmentFile;
import com.eastfair.common.service.AttachmentFileService;
import com.eastfair.common.vo.AttachmentFileVO;
import com.eastfair.core.base.entity.SuperEntity;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.echo.core.EchoService;
import com.eastfair.core.base.R;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.eastfair.boot.request.PageParams;
import com.eastfair.core.context.ContextUtil;

import javax.annotation.Resource;

/**
 * <p>
 * 前端控制器
 * 系统附件表
 * </p>
 *
 * @author clm
 * @date 2022-06-09
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/attachmentFile")
@Api(value = "AttachmentFile", tags = "系统附件表")
@PreAuth(replace = "common:attachmentFile:")
public class AttachmentFileController extends SuperController<AttachmentFileService, Long, AttachmentFile, AttachmentFilePageQuery, AttachmentFileSaveDTO, AttachmentFileUpdateDTO> {
    public static final String[] COMMON_IGNORE_PROPERTIES
            = {"id", "isEnabled", "isDeleted", "projectId", "subsystemId", "tenantId", "createTime", "createdBy", "updatedBy", "updateTime"};
    @Autowired
    private EchoService echoService;

    @Autowired
    private AttachmentFileService attachmentFileService;

    @Resource
    private UserAccountServiceFeign userAccountServiceFeign;

    @Override
    public void handlerResult(IPage<AttachmentFile> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<AttachmentFile> attachmentFileList = list.stream().map((map) -> {
            AttachmentFile attachmentFile = AttachmentFile.builder().build();
            //TODO 请在这里完成转换
            return attachmentFile;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(attachmentFileList));
    }



    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<AttachmentFilePageQuery> params) {
        AttachmentFilePageQuery pageQuery = params.getModel();
        //分页处理
        if(ContextUtil.getProjectId()!=null){
            pageQuery.setProjectId(ContextUtil.getProjectId());
        }
    }

    /**
     * 新增附件记录
     * @param attachmentFileDTOs
     * @return
     */
    @PostMapping("/saveOrUpdateAttachmentFile")
    public R<List<AttachmentFileVO>> addAttachmentFile(@RequestBody List<AttachmentFileDTO> attachmentFileDTOs) {
        List<AttachmentFile> attachmentFiles = new ArrayList<>();
        for (AttachmentFileDTO attachmentFileDTO : attachmentFileDTOs){
            attachmentFiles.add(BeanUtil.copyProperties(attachmentFileDTO, AttachmentFile.class, COMMON_IGNORE_PROPERTIES));
        }
        baseService.saveBatch(attachmentFiles);
        return R.success(ConvertUtil.convertList(attachmentFiles, AttachmentFileVO.class));
    }

    /**
     * 查询
     * @return
     */
    @PostMapping("/queryAttachmentFile")
    public R<List<AttachmentFileVO>> query(@RequestBody AttachmentFileDTO attachmentFileDTO){
        List<AttachmentFile> attachmentFiles = attachmentFileService.query(attachmentFileDTO);
        List<AttachmentFileVO> attachmentFileVOS = ConvertUtil.convertList(attachmentFiles, AttachmentFileVO.class);
        // 处理上传人姓名
        dealName(attachmentFileVOS);
        return R.success(attachmentFileVOS);
    }

    /**
     * 查询
     * @return
     */
    @PostMapping("/queryById/{id}")
    public R<AttachmentFileVO> query(@PathVariable("id") Long id){
        AttachmentFile attachmentFile = baseService.findById(id);
        AttachmentFileVO attachmentFileVO = BeanUtil.copyProperties(attachmentFile, AttachmentFileVO.class);
        return R.success(attachmentFileVO);
    }

    /**
     * 批量查询
     * @param ids
     * @return
     */
    @PostMapping("/queryBatch")
    public R<List<AttachmentFileVO>>  queryBatch(@RequestBody List<Long> ids){
        List<AttachmentFile> attachmentFiles = attachmentFileService.queryBatch(ids);
        List<AttachmentFileVO> attachmentFileVOS = ConvertUtil.convertList(attachmentFiles, AttachmentFileVO.class);
        // 处理上传人姓名
        dealName(attachmentFileVOS);
        return R.success(attachmentFileVOS);
    }

    private void dealName(List<AttachmentFileVO> attachmentFileVOS) {
        if (CollectionUtils.isNotEmpty(attachmentFileVOS)) {
            List<Long> userIds = attachmentFileVOS.stream().map(AttachmentFileVO::getCreatedBy).collect(Collectors.toList());
            UserAccountDto userAccountDto = new UserAccountDto();
            userAccountDto.setUserIds(userIds);
            R<List<UserAccountVo>> listR = userAccountServiceFeign.querySimpleByIds(userAccountDto);
            List<UserAccountVo> data = listR.getData();
            if (CollectionUtil.isNotEmpty(data)) {
                data.forEach(userAccountVo -> {
                    // realName的问题修改
                    if (StringUtils.isBlank(userAccountVo.getRealName())) {
                        userAccountVo.setRealName(userAccountVo.getName());
                    }
                });
                Map<Long, String> userIdNameMap = data.stream().collect(Collectors.toMap(UserAccountVo::getId, UserAccountVo::getRealName));
                for (AttachmentFileVO attachmentFileVO : attachmentFileVOS) {
                    attachmentFileVO.setCreatedByName(userIdNameMap.get(attachmentFileVO.getCreatedBy()));
                }
            }
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/detele/{id}")
    public R detele(@PathVariable("id") Long id){
        baseService.removeById(id);
        return R.success();
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @PostMapping("/detele")
    public R deteleBatch(@RequestBody List<Long> ids){
        baseService.removeByIds(ids);
        return R.success();
    }

}
